package com.pms.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.alarm.entity.KyAlarmRecord;
import com.pms.alarm.service.IKyAlarmRecordService;
import com.pms.controller.BaseController;
import com.pms.entity.UserInfo;
import com.pms.exception.R;
import com.pms.partitionPoints.entity.KyEquipmentInfo;
import com.pms.partitionPoints.entity.KyOrganization;
import com.pms.partitionPoints.service.IKyEquipmentInfoService;
import com.pms.partitionPoints.service.IKyOrganizationEquipmentService;
import com.pms.partitionPoints.service.IKyOrganizationService;
import com.pms.realtime.service.IRealTimeService;
import com.pms.repair.entity.KyRepairDeclare;
import com.pms.repair.service.IKyRepairDeclareService;
import com.pms.rpc.UserService;
import com.pms.validator.Assert;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 宏铭科技
 *
 * @auther ljb
 * @Date 2018/4/18.
 */
@RestController
@RequestMapping(value = "/apiRealtime")
@Api(value="API实施监控接口")
public class ApiRealTimeController extends BaseController{

    @Autowired
    private IKyOrganizationService iKyOrganizationService;
    @Autowired
    private IRealTimeService iRealTimeService;
    @Autowired
    private IKyAlarmRecordService iKyAlarmRecordService;
    @Autowired
    private IKyRepairDeclareService iKyRepairDeclareService;
    @Autowired
    private IKyEquipmentInfoService iKyEquipmentInfoService;
    @Autowired
    UserService userService;
    @Autowired
    IKyOrganizationEquipmentService kyOrganizationEquipmentService;

    @ApiOperation(value = "获取所有实时数据")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="current",value="当前页",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="size",value="每页条数",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="equipmentIds",value="测点ids",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="equipmentStatus",value="测点状态",required = true,dataType = "String",paramType="form")
    })
    public R list(Integer current, Integer size, String equipmentStatus ,String equipmentIds){
        Assert.isNull(current,"current 不能为空");
        Assert.isNull(size,"size 不能为空");
        Assert.isNull(equipmentIds,"equipmentIds 不能为空");
        // 获取当前用户角色
        Map<String,String> currentUserMap=getCurrentUserMap();
        UserInfo currentUserInfo=userService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
        if (null==currentUserInfo||null==currentUserInfo.getId()){ return  R.error(400,"请重新登录");}
        Map<String,Object> userPermiss =userService.getApiPermission(Long.parseLong(currentUserInfo.getId()),1,"实时数据",1,null);
        if (null==userPermiss){
            return  R.error(400,"您没有进入该页面的权限");
        }
        // 通过机构ids 查询所属的groupId
        String groupIds = iKyOrganizationService.getGroupIdsByEq(equipmentIds);
        if (groupIds == null) {
            groupIds = "3";
        }
        String[] groupIdsArr = groupIds.split(",");
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("groupIds", groupIdsArr);
        parameter.put("equipmentStatus",equipmentStatus);
        parameter.put("pageSize",size);
        parameter.put("startRow",(current-1) * size);

        if (StrUtil.isNotEmpty(equipmentIds)) {
            parameter.put("equipmentIds", equipmentIds);
        }
        Page<Map<String,Object>> page = new Page(current,size);
        page = iRealTimeService.selectRealTimeDataPageNew(page, parameter);
        return R.ok().put("page",page);
    }

    @ApiOperation(value = "获取管网监控页面数据（在线设备，报警，报修）")
    @RequestMapping(value = "/getStatusByRoleAndCode",method = RequestMethod.GET)
    public R getStatusByRoleAndCode(
            @RequestHeader("X-Code") String code,
            @RequestHeader("X-groupId") String roleId,
            @RequestHeader("X-groupType") String type){

        Assert.isNull(roleId,"角色id不能为空");
        Assert.isNull(type,"角色类别不能为空");
        Assert.isNull(code,"系统编码不能为空");
        KyOrganization ko = iKyOrganizationService.selectOne(new EntityWrapper<KyOrganization>().
                eq("code",code).eq("organizationGradeId",1));
        Assert.isNull(ko,"系统分区不能为空");
        List<KyOrganization> organizationList = iKyOrganizationService.
                getOrganizationByRoleTypeAndRoleIdAndCompanyCode(
                        Integer.valueOf(type),
                        Long.valueOf(roleId),
                        code);
        String orgIds = "";
        for (KyOrganization kyOrganization : organizationList) {
            orgIds += kyOrganization.getId()+",";
        }
        if (orgIds.length() > 0) {
            orgIds = orgIds.substring(0, orgIds.length() - 1);
        }
        int count = iKyAlarmRecordService.selectNoRead(orgIds);
        int num = 0;
        if (type.equals("1")) {
            num = iKyRepairDeclareService.selectBycountRepairnum(1,code);
        } else {
            num = iKyRepairDeclareService.selectBycountRepairnum(2,roleId);
        }
        int onLine = kyOrganizationEquipmentService.getEquipmentNumByOrgMaxIdAndStatus(ko.getId(),1);
        int offLine = kyOrganizationEquipmentService.getEquipmentNumByOrgMaxIdAndStatus(ko.getId(),2);
        Map<String,Object> map = new HashMap<>();
        if(count>0){
            map.put("alarmStatus",1);
        }else{
            map.put("alarmStatus",0);
        }
        if(num>0){
            map.put("repairStatus",1);
        }else{
            map.put("repairStatus",0);
        }
        map.put("onLine",onLine);
        map.put("offLine",offLine);
        return R.ok().put("data",map);
    }

}
